import subprocess
import time
import socket
import sys

from absl import flags

FLAGS = flags.FLAGS

flags.DEFINE_string("cookie_file",
                    None,
                    "Path of output cookie_file which has authentication token.")

flags.DEFINE_string("userpass_key_file",
                    None,
                    "Path of json file which has owner/username/password fields.")

flags.DEFINE_string("user_agent", None, "User Agent used for login.")

flags.DEFINE_string("remote_host_string",
                    None,
                    "Proxy server. (e.g. socks5://127.0.0.1:12345 for ssh tunnel)")

flags.DEFINE_string("coin_deploy_dir", "", "")

flags.DEFINE_string("ssh_config_file", None, "")


def _find_free_port():
  s = socket.socket()
  s.bind(('', 0))  # Bind to a free port provided by the host.
  port = s.getsockname()[1]  # Return the port number assigned.
  return port


def dynamic_port_forwarding(remote_host_string,
                            ssh_config_file=None,
                            bind_address='127.0.0.1',
                            port=None,
                            coin_deploy_dir=None):
  """Return (Subprocess, port)_pair when it successfully creates a tunnel
  otherwise returns None."""
  cmds = ['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null']

  if ssh_config_file:
    cmds.extend(['-F', ssh_config_file])

  if port is None:
    port = _find_free_port()

  cmds.append(remote_host_string)
  cmds.extend(['-ND', '%s:%d' % (bind_address, port)])

  print("port forwarding cmd:", cmds)
  kwargs = dict()
  if coin_deploy_dir:
    kwargs['cwd'] = coin_deploy_dir
  popen = subprocess.Popen(cmds, **kwargs)

  return (popen, port)


def launch_bithumb_login(cookie_file, userpass_key_file, user_agent=None, proxy_server=None):
  cmds = ["coin/exchange/bithumb/kr_selenium/chrome_cookie_query_auto.sh"]
  if user_agent:
    cmds.append('--user_agent=' + user_agent)

  if cookie_file:
    cmds.append('--cookie_file=' + cookie_file)

  if userpass_key_file:
    cmds.append('--userpass_key_file=' + userpass_key_file)

  if proxy_server:
    cmds.append('--proxy_server=' + proxy_server)

  print("Bithumb login cmd:", cmds)
  output = subprocess.check_output(cmds)
  return output


def main():
  assert FLAGS.cookie_file
  assert FLAGS.userpass_key_file

  popen = None
  try:
    popen, port = dynamic_port_forwarding(FLAGS.remote_host_string,
                                          FLAGS.ssh_config_file,
                                          coin_deploy_dir=FLAGS.coin_deploy_dir)
    time.sleep(10)
    if popen.poll() is None:
      pass

    proxy_server = 'socks5://127.0.0.1:%d' % port
    print("Launch proxy on : ", proxy_server)

    launch_bithumb_login(FLAGS.cookie_file, FLAGS.userpass_key_file, proxy_server=proxy_server)
  except Exception:
    raise
  finally:
    if popen:
      popen.kill()

  return 0


if __name__ == '__main__':
  FLAGS(sys.argv)
  main()
